package com.djsearch.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

import com.djsearch.R;
import com.djsearch.adapter.GroupShopListViewAdapter;
import com.djsearch.bean.GroupBuyGoods;
import com.djsearch.controller.AsyncHandler;
import com.djsearch.controller.IRequest;
import com.djsearch.controller.IResponse;
import com.djsearch.controller.JSONReq;
import com.djsearch.controller.JSONResp;
import com.djsearch.ui.BaseActivity.RequestDataListner;
import com.djsearch.ui.TaoGouActivity.RequestParamStruct;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * 团购列表页面
 * @author chenyang2
 *
 */
public class GroupShopActivity extends BaseActivity  {

	private Context mContext;
	private ListView groupGoodsListView;
	private Button backBtn,locationBtn;//返回，定位按钮
	private RelativeLayout groupShopLayout,paiXuLayout;
	private EditText searchEdit;
	private List<GroupBuyGoods> groupShopGoodsList;
	private List<GroupBuyGoods> nextPageGoodsList;//存放下一页请求的新数据
	private GroupShopListViewAdapter groupShopListViewAdapter;
	private int PAGE = 1;//当前显示到第几页数据
	private ImageView startSearchImg;
	private static String  LATITUDE;
	private static String  LONGITUDE;
	private ImageView bgImg;
	private List<String> groupSortList;
	private List<String> saveGroupSortList;
	private int whichOrder;
	private TextView groupShopText,paixuText;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.group_shop_layout);
		mContext = this;
		groupShopGoodsList = new ArrayList<GroupBuyGoods>();//当前页面数据
		nextPageGoodsList = new ArrayList<GroupBuyGoods>(); //更多（下一页数据）
		groupSortList = new ArrayList<String>();
		saveGroupSortList = new ArrayList<String>();
		//初始化主界面
		initView();
		//初始化主界面相关点击事件
		initOnClick();
		//
		initHandler();
	}
	
	@Override
	public void initView() {
		groupGoodsListView = (ListView)findViewById(R.id.groupGoodsListView);
		groupShopListViewAdapter = new GroupShopListViewAdapter(mContext,groupShopGoodsList);
		groupGoodsListView.setAdapter(groupShopListViewAdapter);
		/**
		 * 滑动到底部自动加载功能
		 */
		groupGoodsListView.setOnScrollListener(new AbsListView.OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				if ( scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
						if (!(progressBarPopuWindow != null && progressBarPopuWindow.isShowing())) {
					        RequestParamStruct.page = PAGE;
					        requestGoodsData(initRequestMap());
						}
					}
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
			}
		});
		backBtn = (Button)findViewById(R.id.groupShopBackBtn);
		locationBtn = (Button)findViewById(R.id.locationBtn);
		bgImg = (ImageView)findViewById(R.id.bgImg);
		String cityName = getSharedPreferences("LOC", 0).getString("city", "北京");
		String a  =  cityName.substring(0,cityName.length()-1);
//		locationBtn.setText(getSharedPreferences("LOC", 0).getString("city", "北京"));
		locationBtn.setText(a); 
		LATITUDE = getSharedPreferences("LOC", 0).getString("latitude", "");
		LONGITUDE = getSharedPreferences("LOC", 0).getString("longitude", "");
		groupShopLayout = (RelativeLayout)findViewById(R.id.groupShopLayout);
		paiXuLayout = (RelativeLayout)findViewById(R.id.paixuLayout);
		groupShopText = (TextView)findViewById(R.id.groupShopText);
		paixuText = (TextView)findViewById(R.id.paixuText);
		searchEdit = (EditText)findViewById(R.id.init_name);
		startSearchImg = (ImageView)findViewById(R.id.startSearchImg);
		initNewRequestParams();
		requestGoodsData(initRequestMap());

	}

	/**
	 * 请求参数的包装
	 * /**
	 * data参数说明:
       {“queryByName”:”手机”,”queryByType”:”5”,”queryByOrder”:”1”,”queryBySecondOrder”:”1”” 
       longitude”:”经度”,” latitude”:”纬度”,”city”:”郑州”,”page”:”1”,”pageNum”:”10”}
       queryByName:团购的商品名字（可为空，当为空的时候，搜索的是全部的，不进行分类）
       queryByType:团购的标示 
       queryByOrder:标示团购排序(1表示离我最近，2表示价格最低，3表示打折最多，4表示购买人数最多)
       queryBySecondOrder:团购里面的分类（比如说餐饮，美食还可以按以上的数字进行分类）
       longitude:表示经度
       latitude:表示纬度
       city:郑州（还有其他的城市， “郑州”这个值由服务端来定）
       page：页码
       pageNum:一页显示数据的条数
	 
	 */
	private Map<String, String> initRequestMap() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("queryByName", RequestParamStruct.queryByName);//商品名称，为空时是请求所有团购商品
		map.put("queryByType", RequestParamStruct.queryByType);//团购标示
		map.put("queryByOrder", RequestParamStruct.queryByOrder);//团购排序
		map.put("queryBySecondOrder", RequestParamStruct.queryBySecondOrder);//团购分类
		map.put("longitude", RequestParamStruct.longitude);//经度
		map.put("latitude", RequestParamStruct.latitude);//纬度
//		map.put("longitude", 
//				getSharedPreferences("LOC", 0).getString("longitude", ""));//经度
//		map.put("latitude", getSharedPreferences("LOC", 0).getString("latitude", ""));
		map.put("city", locationBtn.getText().toString());//城市
		map.put("page", String.valueOf(RequestParamStruct.page));//页码
		map.put("pageNum", RequestParamStruct.pageNum);//一页显示的数据条数
		map.put("distance", RequestParamStruct.distance);//距离
		return map;
	}

	@Override
	public void initOnClick() {
		// TODO Auto-generated method stub
		backBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
//				startActivity(mContext, MainActivity.class, 1);
				finish();
				
			}
		});
		
		setOnRequestDataListner(new RequestDataListner(){
			public void requestData(int position) {
				// TODO Auto-generated method stub
				PAGE = 1;
				groupShopGoodsList.clear();//选择不同的分类时，将当前的分类数据清空
				groupGoodsListView.setVisibility(View.GONE);
				if (sortList.get(0).equals("人气")) {
					RequestParamStruct.queryByOrder = String.valueOf((position+2));
				} else {
					RequestParamStruct.queryBySecondOrder = sortList.get(position);
				}
				if (whichOrder == 1) {
					groupShopText.setText(sortList.get(position));
					paixuText.setText("排序");
				} else if (whichOrder == 2) {
					groupShopText.setText("分类");
					paixuText.setText(sortList.get(position));
				}
				requestGoodsData(initRequestMap());
			}
		});
		
		locationBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent();   
				intent.setClass(mContext, ChooseCityActivity.class);   
				startActivityForResult(intent, 1);
				overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
//				startActivity(mContext, LocInfoActivity.class, 0);
			}
		});
		
		groupShopLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				v.setBackgroundResource(R.drawable.fentiaolan_top_seleted);
//				paiXuLayout.setBackgroundResource(R.drawable.fenlantiao_top);
				sortList.clear();
//				if (saveGroupSortList.size() == 0) {
//					requestSortData();
//				} else {
//					showSearchWayPopupWindow(groupShopLayout, 
//							groupGoodsListView.getHeight(),-getWidth()/2);
//					sortList = saveGroupSortList;
//				}
				whichOrder = 1;
				requestSortData();
				
			}
		});
		paiXuLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				whichOrder = 2;
				sortList.clear();
				sortList.add("人气");
				sortList.add("价格");
				sortList.add("打折");
//				v.setBackgroundResource(R.drawable.fentiaolan_top_seleted);
				groupShopLayout.setBackgroundResource(R.drawable.fenlantiao_top);
				showSearchWayPopupWindow(v, groupGoodsListView.getHeight(),getWidth()/3);
				
			}
		});
		groupGoodsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				startActivity(mContext, GroupShopDetailsActivity.class, 0, 
						groupShopGoodsList.get(position));
			}
		});
		
		startSearchImg.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (searchEdit.getText().toString().equals("")) {
					startAnimation(searchEdit);
				} else {
					/**
					 * 设置相应请求参数，开始请求数据
					 */
					initNewRequestParams();
					RequestParamStruct.queryByName = searchEdit.getText().toString();
					requestGoodsData(initRequestMap());
				}
			}
		});

	}
	
	/**
	 * data参数说明:
       {“queryByName”:”手机”,”queryByType”:”5”,”queryByOrder”:”1”,”queryBySecondOrder”:”1”” 
       longitude”:”经度”,” latitude”:”纬度”,”city”:”郑州”,”page”:”1”,”pageNum”:”10”}
       queryByName:团购的商品名字（可为空，当为空的时候，搜索的是全部的，不进行分类）
       queryByType:团购的标示 
       queryByOrder:标示团购排序(1表示离我最近，2表示价格最低，3表示打折最多，4表示购买人数最多)
       queryBySecondOrder:团购里面的分类（比如说餐饮，美食还可以按以上的数字进行分类）
       longitude:表示经度
       latitude:表示纬度
       city:郑州（还有其他的城市， “郑州”这个值由服务端来定）
       page：页码
       pageNum:一页显示数据的条数
       
       1：进入默认   只传经纬度信息
	 */
	
	
	/**
	 * 请求服务器数据方法
	 * {"queryByOrder":"","distance":"","page":"1","queryByName":"",
	 * "queryBySecondOrder":"",
	 * "longitude":"","latitude":"","queryByType":"5","city":"上海","pageNum":"10"}
	 */
	private void requestGoodsData(Map<String, String> map) {
		IRequest request = new JSONReq("teamshop",map);
		
		HTTP.post(request, new AsyncHandler(){
			@Override
			public void onStart() {
//				showProgressBar(backBtn);
				showDialog("正在加载...");
				
			}
			/**
			 * {"shopPlace":"金水区郑汴路中州大道交叉口西北角建业置地广场","shopPrice":"70.0",
			 * "shopName":"耀莱成龙国际影城单人票","shopDescripe":"仅售20.5元！最高价值70元的耀莱成龙国际影城2D单人电影票，无需预约，不限节假日，2张美团券可以兑换3D单人电影票，特殊限价片需补齐最低差价。极致观影体验，尽在成龙影城！",
			 * "shopUrl":"http:\/\/m.meituan.com\/zhengzhou\/deal\/7870616.html",
			 * "smallImage":"http:\/\/p0.meituan.net\/275.168\/deal\/201212\/19\/132452_5794187.jpg",
			 * "salePrice":"-","bigImage":"http:\/\/p0.meituan.net\/275.168\/deal\/201212\/19\/132452_5794187.jpg",
			 * "telephone":"0371-88817771,0371-55132277",
			 * "hasShop":"1817.0","sale":"-"}
			 */
			@Override
			public void onSuccess(JSONResp response) {
				// TODO Auto-generated method stub
				int result = response.result();
				if(IResponse.Success==result){
					    ++PAGE;
						getDataToResolve(response);
				} else if (IResponse.Fail==result) {
					//返回数据失败
					Toast.makeText(mContext, "没有数据", 5000).show();
				}
					missDialog();
					groupGoodsListView.setVisibility(View.VISIBLE);
			}
			@Override
			public void onFailure(Throwable e, String response) {
				// TODO Auto-generated method stub
//				super.onFailure(e, response);
				missDialog();
				groupGoodsListView.setVisibility(View.VISIBLE);
//				Log.e("GROUP", response);
				Toast.makeText(mContext, "网络传输错误", 5000).show();
//				missProgressBar();
			}
			
		});
	}

	@Override
	void initHandler() {
		// TODO Auto-generated method stub
		
	}

	/**
	 * 解析数据，刷新页面
	 */
	@Override
	void getDataToResolve(JSONResp responseJSON) {
		// TODO Auto-generated method stub

//		JSONArray jsonArray;
		try {
//			jsonArray = responseJSON.getJSONArray("returnMessage");
//			for (int i = 0; i < jsonArray.length(); i++) {
//				JSONObject obJsonObject = jsonArray.getJSONObject(i);
//				GroupBuyGoods groupBuyGoods = new GroupBuyGoods();
//				groupBuyGoods.setShopName(obJsonObject.getString("shopName"));
//				groupBuyGoods.setShopPrice(obJsonObject.getString("shopPrice"));
//				groupBuyGoods.setSalePrice(obJsonObject.getString("salePrice"));
//				groupBuyGoods.setSale(obJsonObject.getString("sale"));
//				groupBuyGoods.setShopDescripe(obJsonObject.getString("shopDescripe"));
//				groupBuyGoods.setShopDistance(obJsonObject.getString("shopDistance"));
//				groupBuyGoods.setSmallImage(obJsonObject.getString("smallImage"));
//				groupBuyGoods.setBigImage(obJsonObject.getString("bigImage"));
//				groupBuyGoods.setShopPlace(obJsonObject.getString("shopPlace"));
//				groupBuyGoods.setTelephone(obJsonObject.getString("telephone"));
//				groupBuyGoods.setHasShop(obJsonObject.getString("hasShop"));
//				groupBuyGoods.setShopUrl(obJsonObject.getString("shopUrl"));
//				nextPageGoodsList.add(groupBuyGoods);
//			}
			Gson gson = new Gson();   
	        Type type = new TypeToken<List<GroupBuyGoods>>(){}.getType();  //指定集合对象属性  
	        List<GroupBuyGoods> fromJson = gson.fromJson(responseJSON.getString("returnMessage"), type); 
	        nextPageGoodsList.addAll(fromJson);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (nextPageGoodsList.size() == 0) {
				//当没有更多的数据了处理
			} else {
				groupShopGoodsList.addAll(nextPageGoodsList);
				nextPageGoodsList.clear();
			}
			groupShopListViewAdapter.refreshData(groupShopGoodsList);
		}
	}
	
	
	/**
	 * {"result":"0","returnMessage":[{"name":"活动单"},{"name":"火锅"},{"name":"电影"},
	 * {"name":"其它餐饮"},{"name":"自助餐"},{"name":"生活服务"},
	 * {"name":"休闲娱乐"},{"name":"异国餐饮"},{"name":"中餐"},{"name":"摄影"},
	 * {"name":"运动健身"},{"name":"商品"},{"name":"丽人"},{"name":"酒店"},
	 * {"name":"文化艺术"},{"name":"旅游"},{"name":"电商"}]}
	 * 
	 */
	
	
	private void requestSortData() {
        IRequest request = new JSONReq("groupshop_sort");
		HTTP.post(request, new AsyncHandler(){
			@Override
			public void onStart() {
//				showProgressBar(backBtn);
				showDialog("正在加载...");
			}
			@Override
			public void onSuccess(JSONResp response) {
				// TODO Auto-generated method stub
				int result = response.result();
				if(IResponse.Success==result){
						getSortDataToResolve(response);
						showSearchWayPopupWindow(groupShopLayout, groupGoodsListView.getHeight(),-getWidth()/2);
				} else if (IResponse.Fail==result) {
					//返回数据失败
					Toast.makeText(mContext, "没有数据", 5000).show();
				}
					missDialog();
//				    missProgressBar();
			}
			@Override
			public void onFailure(Throwable e, String response) {
				missDialog();
				Toast.makeText(mContext, "网络传输错误", 5000).show();
			}
			
		});
	}
	
	private void getSortDataToResolve(JSONResp responseJSON) {
		
		JSONArray jsonArray;
		try {
			jsonArray = responseJSON.getJSONArray("returnMessage");
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject obJsonObject = jsonArray.getJSONObject(i);
				groupSortList.add(obJsonObject.getString("name"));
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			sortList = groupSortList;
			if (groupSortList.size() != 0) {
				for (int i=0;i<groupSortList.size();i++) {
					saveGroupSortList.add(groupSortList.get(i));
				}
			}
		}
			
	}
	
	
	/**
	 * 请求数据 data参数数据实体类
	 * 当请求条件变化时，相应赋予该实体类的属性值
	 * @author chenyang2
	 *
	 */
	static class RequestParamStruct{
		static String queryByName = "";//商品名称，为空时是请求所有团购商品
		static String queryByType = "5";//团购标示(暂时不用)
		static String queryByOrder = "2";//团购排序,,人气，价格，打折

		static String queryBySecondOrder = "";//团购分类
		static String longitude = LONGITUDE; //经度  getSharedPreferences("LOC", 0).getString("city", "北京")
		static String latitude = LATITUDE;//纬度
		static String city = "上海";//城市
		static int page = 1;//页码
		static String pageNum = "10";//一页显示的数据条数 
		static String distance = "";//500，1000，1500，2000，3000，5000，更远(1 - 7)
	}
	
	
	@Override   
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {   
	       // TODO Auto-generated method stub    
	       Bundle bundle;   
	       switch (requestCode) {   
	       case 1:   
	           if (resultCode == RESULT_OK){   
	               bundle = data.getExtras();   
	               String beginName = bundle.getString("NAME"); 
	               locationBtn.setText(beginName);
	               RequestParamStruct.city = beginName;
	               initNewRequestParams();
	               requestGoodsData(initRequestMap());
	           }  
	       default:   
	           break;   
	       }   
	    }  
	
	
	/**
	 * 点击返回键
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			startActivity(mContext, MainActivity.class, 1);
		}
		return false;
	}
	
	/**
	 * 当筛选条件变化时 调用该函数
	 * 
	 * 比如切换城市时，调用该方法
	 */
	private void initNewRequestParams() {
		groupShopGoodsList.clear();
		PAGE = 1;
		RequestParamStruct.page = 1;
		RequestParamStruct.queryByName = "";
		RequestParamStruct.queryByOrder = "";//团购排序,,人气，价格，打折
		RequestParamStruct.queryBySecondOrder = "";//团购分类
		RequestParamStruct.longitude = ""; //经度  getSharedPreferences("LOC", 0).getString("city", "北京")
		RequestParamStruct.latitude = "";//纬度
	}
}
